package com.igroupes.ovineherd.aop;


import com.igroupes.ovineherd.constant.Constants;
import com.igroupes.ovineherd.dto.UserInfo;
import com.igroupes.ovineherd.enums.ErrorCode;
import com.igroupes.ovineherd.exception.OvineHerdException;
import com.igroupes.ovineherd.rpc.client.UserService;
import com.igroupes.ovineherd.vo.ResultVO;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginUserHandlerInterceptorAdapter extends HandlerInterceptorAdapter {

    private UserService userService;

    public LoginUserHandlerInterceptorAdapter(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!HandlerMethod.class.isAssignableFrom(handler.getClass())) {
            return super.preHandle(request, response, handler);
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String token = request.getHeader(Constants.LOGIN_TOKEN_KEY);
        // 获取用户信息
        Exception tmpEx = null;
        try {
            request.setAttribute(Constants.USER_INFO_REQUEST_ATTRIBUTE_KEY, getUserInfo(token));
        } catch (Exception ex) {
            tmpEx = ex;
        }
        LoginUser typeAnno = handlerMethod.getBeanType().getAnnotation(LoginUser.class);
        // 如果需要登录，但是没有获取到用户信息
        if (typeAnno != null) {
            SkipLogin skipLogin = handlerMethod.getMethodAnnotation(SkipLogin.class);
            if (skipLogin == null && tmpEx != null) {
                throw tmpEx;
            }
        } else {
            LoginUser methodAnno = handlerMethod.getMethodAnnotation(LoginUser.class);
            if (methodAnno != null && tmpEx != null) {
                throw tmpEx;
            }
        }
        return true;
    }


    private UserInfo getUserInfo(String token) {
        ResultVO<UserInfo> userInfoResultVO = userService.infoByToken(token);
        if (userInfoResultVO.getCode() != ResultVO.CODE_OK) {
            throw new OvineHerdException(userInfoResultVO.getMsg());
        }
        return userInfoResultVO.getData();
    }


}
